package com.bookstore.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class FileUpload {

    public static String uploadImg(MultipartFile imgFile, HttpServletRequest request) throws IOException {
        FileUtils fileUtils = new FileUtils();
        //如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解
        String file = null;
        if (!imgFile.isEmpty()) {
            try {
                String realPath = request.getSession().getServletContext().getRealPath("/upload/bookimg");
                System.out.println(realPath + imgFile.getOriginalFilename());
                file = System.currentTimeMillis() + imgFile.getOriginalFilename();
                //这里将上传得到的文件保存至 d:\\temp\\file 目录
                fileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, file));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  file;//上传成功则跳转至此success.jsp页面
    }

    public static String uploadPDF(MultipartFile pdfFile, HttpServletRequest request) throws IOException {
        //如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解
        String file = null;
        if (!pdfFile.isEmpty()) {
            try {
                String realPath = request.getSession().getServletContext().getRealPath("/upload");
                file = System.currentTimeMillis() + pdfFile.getOriginalFilename();
                //这里将上传得到的文件保存至 d:\\temp\\file 目录
                FileUtils.copyInputStreamToFile(pdfFile.getInputStream(), new File(realPath, file));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  file;
    }
}
